{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED\n",
    "from concurrent.futures import Future\n",
    "from multiprocessing import Pool\n",
    "\n",
    "#未来对象，task的返回容器\n",
    "\n",
    "\n",
    "#线程池， 为什么要线程池\n",
    "#主线程中可以获取某一个线程的状态或者某一个任务的状态，以及返回值\n",
    "#当一个线程完成的时候我们主线程能立即知道\n",
    "#futures可以让多线程和多进程编码接口一致\n",
    "import time\n",
    "\n",
    "def get_html(times):\n",
    "    time.sleep(times)\n",
    "    print(\"get page {} success\".format(times))\n",
    "    return times\n",
    "\n",
    "\n",
    "\n",
    "executor = ThreadPoolExecutor(max_workers=2)\n",
    "#通过submit函数提交执行的函数到线程池中, submit 是立即返回\n",
    "# task1 = executor.submit(get_html, (3))\n",
    "# task2 = executor.submit(get_html, (2))\n",
    "\n",
    "\n",
    "#要获取已经成功的task的返回\n",
    "urls = [3,2,4]\n",
    "all_task = [executor.submit(get_html, (url)) for url in urls]\n",
    "wait(all_task, return_when=FIRST_COMPLETED)\n",
    "print(\"main\")\n",
    "# for future in as_completed(all_task):\n",
    "#     data = future.result()\n",
    "#     print(\"get {} page\".format(data))\n",
    "#通过executor的map获取已经完成的task的值\n",
    "# for data in executor.map(get_html, urls):\n",
    "#     print(\"get {} page\".format(data))\n",
    "\n",
    "\n",
    "# # done方法用于判定某个任务是否完成\n",
    "# print(task1.done())\n",
    "# print(task2.cancel())\n",
    "# time.sleep(3)\n",
    "# # done方法用于判定某个任务是否完成\n",
    "# print(task1.done())\n",
    "\n",
    "# #result方法可以获取task的执行结果\n",
    "# print(task1.result())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
